package net.hn.hnms.biz.plan.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.hn.hnms.biz.plan.domain.ExecutionSale;
import net.hn.hnms.biz.plan.mapper.ExcutionSaleMapper;
import net.hn.hnms.biz.plan.request.ExecutionSaleReq;
import net.hn.hnms.biz.plan.service.ExecutionSaleService;
import net.hn.hnms.biz.plan.vo.ExecutionSaleVo;
import net.hn.hnms.biz.plan.vo.SalesStatisticsVo;
import net.hn.hnms.sys.common.core.constant.Constants;
import net.hn.hnms.sys.common.core.domain.ResponsePage;
import net.hn.hnms.sys.common.core.exception.HuaNengException;
import net.hn.hnms.sys.common.mybatis.core.page.PageQuery;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ly
 * 销售计划服务层实现
 * @date 2022-09-22
 */

@Service
public class ExecutionSaleServiceImpl extends BaseService<ExecutionSale, ExecutionSaleVo> implements ExecutionSaleService {

    private ExcutionSaleMapper executionSaleMapper;

    public ExecutionSaleServiceImpl(ExcutionSaleMapper executionSaleMapper) {
        this.executionSaleMapper = executionSaleMapper;
    }

    /**
     * @param executionSale
     * @param pageQuery 查询回采计划列表
     */
    @Override
    public ResponsePage<ExecutionSaleVo> selectPageList(ExecutionSaleReq executionSale, PageQuery pageQuery) {

        Page<ExecutionSale> page = executionSaleMapper.selectPage(pageQuery.build(), buildQuery(executionSale).orderByDesc(ExecutionSale::getExecutionDate).orderByDesc(ExecutionSale::getCreateTime));
        List<ExecutionSaleVo> list = page.getRecords().stream().map(o -> convertWithUser(o,ExecutionSaleVo.class)).collect(Collectors.toList());
        return new ResponsePage<>(list, page.getTotal());
    }

    @Override
    public SalesStatisticsVo selectSalesStatisticsVo(ExecutionSaleReq req, String month) {
        List<String> list = new ArrayList<>();
        req.setDateTimeRange(list);
        SalesStatisticsVo vo = new SalesStatisticsVo();

        if (StrUtil.isBlank(month)) {
            Date date = new Date();
            Date yearBegin = DateUtil.beginOfYear(date);
            Date yearEnd = DateUtil.endOfYear(date);
            Date monthBegin = DateUtil.beginOfMonth(date);
            Date monthEnd = DateUtil.endOfMonth(date);

            list.add(DateUtil.format(monthBegin, "yyyy-MM-dd"));
            list.add(DateUtil.format(monthEnd, "yyyy-MM-dd"));
            List<ExecutionSale> montList = executionSaleMapper.selectList(buildQuery(req).orderByDesc(ExecutionSale::getExecutionDate).orderByDesc(ExecutionSale::getCreateTime));
            list.clear();

            list.add(DateUtil.format(yearBegin, "yyyy-MM-dd"));
            list.add(DateUtil.format(yearEnd, "yyyy-MM-dd"));
            List<ExecutionSale> yearList = executionSaleMapper.selectList(buildQuery(req).orderByDesc(ExecutionSale::getExecutionDate).orderByDesc(ExecutionSale::getCreateTime));

            montList.forEach(m -> {
                vo.setMonth(vo.getMonth().add(m.getSalesVolume()));
            });

            yearList.forEach(m -> {
                vo.setYear(vo.getYear().add(m.getSalesVolume()));
            });
            vo.setSaleCount(vo.getYear());

            return vo;
        } else {
            Date date = new Date();
            date.setMonth(Integer.parseInt(month) - 1);
            Date monthBegin = DateUtil.beginOfMonth(date);
            Date monthEnd = DateUtil.endOfMonth(date);
            list.add(DateUtil.format(monthBegin, "yyyy-MM-dd"));
            list.add(DateUtil.format(monthEnd, "yyyy-MM-dd"));
            List<ExecutionSale> montList = executionSaleMapper.selectList(buildQuery(req).orderByDesc(ExecutionSale::getExecutionDate).orderByDesc(ExecutionSale::getCreateTime));
            montList.forEach(m -> {
                vo.setSaleCount(vo.getSaleCount().add(m.getSalesVolume()));
            });
            return vo;
        }
    }


    /**
     * 构造查询条件
     *
     * @param req
     * @return LambdaQueryWrapper<PlanDevelopment> 查询条件
     */
    private LambdaQueryWrapper<ExecutionSale> buildQuery(ExecutionSaleReq req) {
        LambdaQueryWrapper<ExecutionSale> lqw = new LambdaQueryWrapper<ExecutionSale>()
                .ge(req.getBeginDateTime() != null, ExecutionSale::getExecutionDate, req.getBeginDateTime())
                .le(req.getEndDateTime() != null, ExecutionSale::getExecutionDate, req.getEndDateTime())
                .eq(StrUtil.isNotBlank(req.getSalesDestination()), ExecutionSale::getSalesDestination, req.getSalesDestination())
                .eq(StrUtil.isNotBlank(req.getTypeCoal()), ExecutionSale::getTypeCoal, req.getTypeCoal())
                .eq(StrUtil.isNotBlank(req.getMineCode()), ExecutionSale::getMineCode, req.getMineCode());
        return lqw;
    }


    /**
     * @param executionSaleReq 查询掘进计划列表
     */
    @Override
    public List<ExecutionSaleVo> selectList(ExecutionSaleReq executionSaleReq) {
        List<ExecutionSale> list = executionSaleMapper.selectList(buildQuery(executionSaleReq));
        ArrayList<ExecutionSaleVo> executionSaleVos = new ArrayList<>();
       return list.stream().map(o -> convertWithUser(o, ExecutionSaleVo.class)).collect(Collectors.toList());
    }

    /**
     * @param executionSale 新增回采计划
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(ExecutionSaleReq executionSale) {
        //自动生成 计划名称 计划编号
        ExecutionSale insertObj = new ExecutionSale();
       
        BeanUtils.copyProperties(executionSale,insertObj);
        //insertObj.setStatus("0");

        QueryWrapper<ExecutionSale> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("execution_date", insertObj.getExecutionDate()).eq("sales_destination",executionSale.getSalesDestination()).eq("type_coal",executionSale.getTypeCoal());
        if (executionSaleMapper.selectCount(queryWrapper) > 0) {
            throw new HuaNengException(Constants.FAIL, "已存在同一时段的内容");
        }
        return executionSaleMapper.insert(insertObj);
    }

    /**
     * @param idList 批量删除
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(List<String> idList) {
        executionSaleMapper.deleteBatchIds(idList);
    }

    /**
     * @param executionSale 单个修改 按照主键修改信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateById(ExecutionSaleReq executionSale) {
        if (StrUtil.isBlank(executionSale.getSaleExecutionId())) {
            throw new HuaNengException(Constants.FAIL, "id不能为空");
        }
        ExecutionSale updateObj = new ExecutionSale();
       BeanUtils.copyProperties(executionSale,updateObj);


        QueryWrapper<ExecutionSale> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("execution_date", updateObj.getExecutionDate()).eq("sales_destination",updateObj.getSalesDestination()).eq("type_coal",updateObj.getTypeCoal()).eq("sales_volume",updateObj.getSalesVolume());
        if (executionSaleMapper.selectCount(queryWrapper) > 0) {
            throw new HuaNengException(Constants.FAIL, "已存在相同时间段的数据");
        }
        int updateCount = executionSaleMapper.updateById(updateObj);
        if (updateCount == 0) {
            throw new HuaNengException(Constants.FAIL, "数据不存在");
        }

    }

    /**
     * @param id 按主键id查询详情
     */
    @Override
    public ExecutionSaleVo selectDetailById(String id) {
        ExecutionSale executionSale = executionSaleMapper.selectById(id);
        if (executionSale == null) {
            throw new HuaNengException(Constants.FAIL, "数据不存在");
        }
        return convertWithUser(executionSale, ExecutionSaleVo.class);
    }


    /**
     * 启用/禁用
     *
     * @param id     数据id
     * @param status status: 0:启用 1:禁用
     */
    /*public void changeStatus(String id, Integer status) {
        if (status == 1 || status == 0) {
            ExecutionSale planMining = executionSaleMapper.selectById(id);
            if (planMining == null) {
                throw new HuaNengException(Constants.FAIL, "数据不存在");
            }
            planMining.setStatus(status + "");
            int res = executionSaleMapper.updateById(planMining);
            if (res == 0) {
                throw new HuaNengException(Constants.FAIL, "数据不存在");
            }
            return;
        }
        throw new HuaNengException(Constants.FAIL, "传入的参数错误");
    }*/
}
